// pages/combos/combos.ts
import { MerchantAPI } from '../../utils/api'

interface Combo {
  comboId: string | number;
  name: string;
  description: string;
  imageUrl: string;
  marketPrice: number;
  regionPrice: number;
  status: number | string;
  statusText: string;
  sortOrder: string | number;
  createdAt?: string;
}

interface CombosPageData {
  hasLogin: boolean;
  loading: boolean;
  refreshing: boolean;
  headerHeight: number;
  navBarHeight: number;
  combos: Combo[];
  filteredCombos: Combo[];
  stats: {
    totalCount: number;
    sellingCount: number;
    offShelfCount: number;
  };
  activeStatus: string;
  searchKeyword: string;
  selectedCombos: string[];
  page: number;
  limit: number;
  hasMore: boolean;
}

const STATUS_TEXT_MAP: Record<number | string, string> = {
  0: '已下架',
  1: '上架中'
};

Page({
  data: {
    hasLogin: false,
    loading: false,
    refreshing: false,
    headerHeight: 400,
    navBarHeight: 88,
    combos: [],
    filteredCombos: [],
    stats: {
      totalCount: 0,
      sellingCount: 0,
      offShelfCount: 0
    },
    activeStatus: '',
    searchKeyword: '',
    selectedCombos: [],
    page: 1,
    limit: 10,
    hasMore: true
  } as CombosPageData,

  onLoad() {
    this.checkLoginStatus();
    // 立即计算一次，使用默认值
    this.calculateHeaderHeight();
    if (this.data.hasLogin) {
      this.loadCombos();
      this.updateStats();
    }
  },

  onShow() {
    const wasLoggedIn = this.data.hasLogin;
    this.checkLoginStatus();
    // 每次显示时重新计算高度
    this.calculateHeaderHeight();
    if (!wasLoggedIn && this.data.hasLogin) {
      this.loadCombos();
    }

    const shouldRefresh = wx.getStorageSync('combos_should_refresh');
    if (shouldRefresh) {
      wx.removeStorageSync('combos_should_refresh');
      this.setData({ page: 1, hasMore: true });
      this.loadCombos(true);
    }
  },

  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    if (token && userInfo) {
      this.setData({ hasLogin: true });
    } else {
      this.setData({ hasLogin: false });
    }
  },

  goToLogin() {
    wx.navigateTo({
      url: '/pages/auth/auth'
    });
  },

  calculateHeaderHeight() {
    setTimeout(() => {
      const query = wx.createSelectorQuery().in(this);
      query.select('.weui-navigation-bar__inner').boundingClientRect();
      query.select('.fixed-header').boundingClientRect();
      query.exec((res: any) => {
        const navBarRect = res[0];
        const fixedHeaderRect = res[1];
        if (fixedHeaderRect && navBarRect) {
          const navBarHeight = navBarRect.height;
          const fixedHeaderHeight = fixedHeaderRect.height;
          const totalHeight = navBarHeight + fixedHeaderHeight - 80;
          this.setData({
            headerHeight: totalHeight > navBarHeight ? totalHeight : navBarHeight,
            navBarHeight: navBarHeight
          });
        } else {
          this.setData({
            headerHeight: 400,
            navBarHeight: 88
          });
        }
      });
    }, 200);
  },

  async loadCombos(isRefresh = false) {
    if (isRefresh) {
      this.setData({
        page: 1,
        combos: [],
        filteredCombos: [],
        hasMore: true
      });
    }

    if (!this.data.hasMore && !isRefresh) {
      return;
    }

    this.setData({
      loading: true,
      refreshing: isRefresh
    });

    try {
      const params: any = {
        pageNum: this.data.page,
        pageSize: this.data.limit
      };

      if (this.data.activeStatus !== '') {
        params.status = Number(this.data.activeStatus);
      }
      if (this.data.searchKeyword.trim()) {
        params.name = this.data.searchKeyword.trim();
      }

      const response = await MerchantAPI.getCombos(params);
      const rows = response?.rows || response?.data?.rows || [];
      const totalValue = response?.total ?? response?.data?.total;

      const mapped = rows.map((item: any) => this.normalizeCombo(item));
      const combos = isRefresh ? mapped : [...this.data.combos, ...mapped];
      const hasMore = typeof totalValue === 'number'
        ? combos.length < totalValue
        : rows.length >= this.data.limit;

      // 为每个套餐添加isSelected标记
      const filteredCombos = this.addSelectedFlag(combos);

      this.setData({
        combos,
        filteredCombos,
        hasMore,
        page: this.data.page + 1
      });
      // 不在这里调用统计，统计应该只在初始化时调用一次

      if (isRefresh) {
        this.setData({ selectedCombos: [] });
        // 数据加载完成后重新计算高度，确保准确
        setTimeout(() => {
          this.calculateHeaderHeight();
        }, 100);
      }
    } catch (error) {
      console.error('加载套餐列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        loading: false,
        refreshing: false
      });
    }
  },

  normalizeCombo(item: any): Combo {
    const status = typeof item.status === 'number' ? item.status : (item.status ? 1 : 0);
    return {
      comboId: String(item.comboId || ''), // 确保 comboId 始终是字符串
      name: item.name || '',
      description: item.description || '',
      imageUrl: item.imageUrl || '/images/empty-messages.png',
      marketPrice: Number(item.marketPrice ?? 0),
      regionPrice: Number(item.regionPrice ?? 0),
      status,
      statusText: STATUS_TEXT_MAP[status] || '未知状态',
      sortOrder: item.sortOrder || '1',
      createdAt: item.createTime || item.createdAt || ''
    };
  },

  /**
   * 加载套餐统计数据（获取所有套餐进行统计）
   */
  async updateStats() {
    try {
      // 获取所有套餐（不带任何筛选条件）
      const response = await MerchantAPI.getCombos({
        pageNum: 1,
        pageSize: 1000 // 获取足够多的套餐用于统计
      });
      
      const allCombos = response?.rows || response?.data?.rows || [];
      console.log('📊 套餐统计数据 - 总套餐数:', allCombos.length);
      
      // 打印前10个套餐的状态用于调试
      allCombos.forEach((c: any, index: number) => {
        if (index < 10) {
          console.log(`套餐${index + 1}: ${c.comboName || c.name}, status=${c.status}`);
        }
      });
      
      const stats = {
        totalCount: allCombos.length,
        sellingCount: allCombos.filter((c: any) => Number(c.status) === 1).length,
        offShelfCount: allCombos.filter((c: any) => Number(c.status) === 0).length
      };
      
      console.log('📊 套餐统计:', stats);
      this.setData({ stats });
    } catch (error) {
      console.error('❌ 加载套餐统计失败:', error);
    }
  },

  filterByStatus(e: any) {
    const status = e.currentTarget.dataset.status;
    this.setData({
      activeStatus: status,
      selectedCombos: [],
      page: 1,
      hasMore: true
    });
    this.loadCombos(true);
  },

  onSearchInput(e: any) {
    this.setData({
      searchKeyword: e.detail.value
    });
  },

  onSearchConfirm() {
    this.setData({
      page: 1,
      hasMore: true
    });
    this.loadCombos(true);
  },

  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.loadCombos(true);
  },

  toggleSelectCombo(e: any) {
    // 确保ID统一转为字符串类型
    const comboId = String(e.currentTarget.dataset.id || '');
    if (!comboId) return;
    
    const selectedCombos = [...this.data.selectedCombos];
    const index = selectedCombos.indexOf(comboId);
    
    if (index >= 0) {
      // 如果已选中，则取消选中
      selectedCombos.splice(index, 1);
    } else {
      // 如果未选中，则添加
      selectedCombos.push(comboId);
    }
    
    console.log('选中的套餐ID列表:', selectedCombos);
    console.log('当前comboId:', comboId, '类型:', typeof comboId);
    
    // 先用新的selectedCombos计算filteredCombos
    const filteredCombos = this.data.combos.map(combo => ({
      ...combo,
      isSelected: selectedCombos.indexOf(String(combo.comboId)) >= 0
    }));
    
    console.log('更新后的filteredCombos:', filteredCombos.map(c => ({ id: c.comboId, selected: c.isSelected })));
    
    // 强制更新视图
    this.setData({
      selectedCombos: selectedCombos,
      filteredCombos: filteredCombos
    });
  },

  // 为套餐数据添加isSelected标记
  addSelectedFlag(combos: Combo[]): any[] {
    const selectedCombos = this.data.selectedCombos;
    return combos.map(combo => ({
      ...combo,
      isSelected: selectedCombos.indexOf(String(combo.comboId)) >= 0
    }));
  },

  async batchOperation(e: any) {
    const operation = e.currentTarget.dataset.operation;
    const { selectedCombos } = this.data;
    
    if (selectedCombos.length === 0) {
      wx.showToast({
        title: '请先选择套餐',
        icon: 'none'
      });
      return;
    }

    const operationText = operation === 'on_shelf' ? '上架' : '下架';
    const status = operation === 'on_shelf' ? 1 : 0;

    wx.showModal({
      title: '批量操作',
      content: `确定要批量${operationText}选中的${selectedCombos.length}个套餐吗？`,
      success: async (res) => {
        if (res.confirm) {
          this.setData({ loading: true });
          try {
            // 使用批量更新状态接口
            await MerchantAPI.updateComboStatus({
              comboIds: selectedCombos,
              status: status
            });

            wx.showToast({
              title: `批量${operationText}成功`,
              icon: 'success'
            });

            this.setData({ selectedCombos: [], page: 1, hasMore: true });
            this.loadCombos(true);
            this.updateStats();
          } catch (error) {
            wx.showToast({
              title: `批量${operationText}失败`,
              icon: 'none'
            });
          } finally {
            this.setData({ loading: false });
          }
        }
      }
    });
  },

  async toggleComboStatus(e: any) {
    const combo = e.currentTarget.dataset.combo;
    const newStatus = combo.status === 1 || combo.status === '1' ? 0 : 1;
    const statusText = newStatus === 1 ? '上架' : '下架';

    try {
      await MerchantAPI.updateComboStatus({
        comboIds: [combo.comboId],
        status: newStatus
      });

      wx.showToast({
        title: `套餐已${statusText}`,
        icon: 'success'
      });

      this.setData({ page: 1, hasMore: true });
      this.loadCombos(true);
      this.updateStats();
    } catch (error) {
      console.error('更新状态失败', error);
      wx.showToast({
        title: `${statusText}失败`,
        icon: 'none'
      });
    }
  },

  openCreateForm() {
    if (!this.data.hasLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: '/pages/combo-form/combo-form?mode=create'
    });
  },

  handleEditCombo(e: any) {
    const combo = e.currentTarget.dataset.combo;
    if (!combo) return;
    if (!this.data.hasLogin) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.navigateTo({
      url: `/pages/combo-form/combo-form?mode=edit&comboId=${combo.comboId}`
    });
  },

  handleDeleteCombo(e: any) {
    const combo = e.currentTarget.dataset.combo;
    if (!combo) return;
    
    wx.showModal({
      title: '删除套餐',
      content: '删除后不可恢复，确定继续？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...', mask: true });
          try {
            await MerchantAPI.deleteCombo([combo.comboId]);
            wx.showToast({
              title: '已删除',
              icon: 'success'
            });
            this.loadCombos(true);
          } catch (error) {
            console.error('删除套餐失败', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  onRefresh() {
    this.loadCombos(true);
  },

  loadMore() {
    if (!this.data.loading && this.data.hasMore) {
      this.loadCombos();
    }
  }
});


